package com.wnxy.portal.common.util;

import cn.hutool.jwt.JWTUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenUtil {

    @Value("${jwt.secret}")
    private String secret;

    /**
     * 生成token
     */
    public String createToken(Long userId,String nickName) {
        Map<String,Object> payload = new HashMap<>();
        payload.put("userId",String.valueOf(userId));
        payload.put("nickName",nickName);

        // 获取登录用户的ip地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipAddr = IpUtil.getIpAddr(request);
        payload.put("ip",ipAddr);

        // 生成token
        String token = JWTUtil.createToken(payload, secret.getBytes());
        return token;
    }

    /**
     * 校验token
     */
    public boolean verify(String token) {
        return JWTUtil.verify(token,secret.getBytes());
    }

}
